// pages/cards/cards.js
const util = require('../../utils/util.js')
const app = getApp()
Page({

  /**
   * 页面的初始数据
   */
  data: {
    /*  */
    showNoDataIcon:false,
    userInfo_chezhu: null,
    /*  */
    tabData: [
      {
        tabName: '未使用'
      },
      {
        tabName: '已使用'
      },
      {
        tabName: '已过期'
      }
    ],  //menu-tab的数据
    activeIndex: '0',
    /* 卡片列表请求参数 */
    cardListArgs: {
      mobile: '',
      page: 1,
      pageSize: 10,
      status: '0',   //卡片状态:0、未使用，1、已使用，2、已过期
    },
    /* 页码 */
    cardPage: {
      '0': 1,
      "1": 1,
      "2": 1
    },
    /* 卡片列表数据 */
    cardData: {
      '0': [],
      "1": [],
      "2": []
    },
    /*  */
  },
  dateFormat1: function (str) {
    return app.globalData.dateFormat1(str)
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    //获取用户信息
    this.setData({
      userInfo_chezhu: app.globalData.get_userInfo()
    })
    if(!this.data.userInfo_chezhu.mobile){
      this.setData({
        'cardData.0':[],
        'cardData.1':[]
      })
    }
    if(this.data.userInfo_chezhu.mobile&&!this.data.cardData[this.data.activeIndex+''].length){
      //
      this.setData({
        'cardListArgs.mobile': this.data.userInfo_chezhu.mobile
      })
      //
      this.getCard(true)
    }
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },
  /* 获取卡片列表数据 */
  getCard: function (isRefresh) {
    this.setData({
      showNoDataIcon: false
    })
    /* 下拉刷新 */
    if(isRefresh){
      let pageNum = this.data.cardPage[this.data.activeIndex+'']
      let existData = this.data.cardData[this.data.activeIndex+'']
      pageNum = 1
      existData.splice(0,existData.length)
      this.setData({
        [`cardPage.${this.data.activeIndex}`]:pageNum,
        [`cardData.${this.data.activeIndex}`]:existData
      })
    }
    wx.showLoading({
      title: '获取数据',
      mask:true
    })
    return new Promise((resolve, reject) => {
      this.setData({
        'cardListArgs.status':this.data.activeIndex+'',
        'cardListArgs.page': this.data.cardPage[this.data.activeIndex]
      })
      wx.request({
        url: app.globalData.Url + '/wx/getCard',
        method: 'POST',
        header:this.data.userInfo_chezhu.header,
        data: util.json2Form(this.data.cardListArgs),   //
        success: res => {
          console.log(res)
          //判断token是否过期
          if(app.globalData.check_token(res.data.code))return new Promise((resolve,reject)=>{})
          //
          if (res.data.code == '1') {
            /* 无数据 */
            if (!res.data.body.data.length) {
              if(!this.data.cardData[this.data.activeIndex+''].length){
                this.setData({
                  showNoDataIcon: true
                })
              }
              return resolve()
            }
            let existData = this.data.cardData[this.data.activeIndex]
            res.data.body.data.forEach(item => {
              item.useStartTime = this.dateFormat1.call(this, item.useStartTime)
              item.useEndTime = this.dateFormat1.call(this, item.useEndTime)
              item.openAnimationLoad = false
              existData.push(item)
            })
            //
            let pageNum = this.data.cardPage[this.data.activeIndex] * 1
            pageNum += 1
            this.setData({
              showNoDataIcon: false,
              ['cardPage.' + this.data.activeIndex]: pageNum,
              ['cardData.' + this.data.activeIndex]: existData
            })
            resolve()
          } else {
            wx.showToast({
              icon: 'none',
              title: res.data.msg
            })
            if(!this.data.cardData[this.data.activeIndex+''].length){
              this.setData({
                showNoDataIcon: true
              })
            }
            reject()
          }
        },
        fail: err => {
          console.log(err)
          wx.showToast({
            icon: 'none',
            title: '获取数据失败'
          })
          if(!this.data.cardData[this.data.activeIndex+''].length){
            this.setData({
              showNoDataIcon: true
            })
          }
          reject()
        },
        complete: () => {
          wx.hideLoading()
        }
      })
    })
  },
  /* 卡片类型切换 */
  getActiveIndex: function (e) {
    if(!this.data.userInfo_chezhu.mobile){
      wx.switchTab({
        url: '/pages/personal/personal',
      })
      return
    }
    //console.log(e.detail)
    if (this.data.cardListArgs.status === e.detail.activeIndex) return
    this.setData({
      'activeIndex': e.detail.activeIndex,
      'cardListArgs.status': e.detail.activeIndex
    })
    //
    if (this.data.cardPage[e.detail.activeIndex + ''] === 1 && !this.data.cardData[e.detail.activeIndex + ''].length) {
      this.getCard()
    }
  },
  /* 显示有省略号的价格 */
  showPrice(e) {
    //console.log(e)
    wx.showToast({
      icon: 'none',
      title: e.currentTarget.dataset.price
    })
  },
  /* 跳转到卡券详情 */
  showCardDetail(e) {
    //console.log(e)
    let { info }= e.currentTarget.dataset
    /* cardno  type */
    app.globalData.setNeedAnimation.call(this, 'cardData.' + this.data.activeIndex, this.data['cardData'][this.data.activeIndex + ''], e.currentTarget.dataset.index).then(() => {
      /*  */
      wx.navigateTo({
        url: '/pages/details/details',
        success: res => {
          res.eventChannel.emit('open-card-detail', {
            cardno: info.cardNo,
            status: this.data.activeIndex
          })
        }
      })
    })
  },
  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
    this.getCard(true).then(()=>{
      wx.stopPullDownRefresh({
        complete: (res) => {},
      })
    })
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
    this.getCard()
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})